package pers.cz.mock;

import pers.cz.config.Config;
import pers.cz.util.ICollectGenerator;
import redis.clients.jedis.Jedis;

import java.util.Map;

/**
 * 多线程录制sql
 * @program: postgirl-collection-client
 * @description: InterfaceSqlThread
 * @author: Cheng Zhi
 * @create: 2022-02-22 15:44
 **/
public class InterfaceSqlThread implements ICollectGenerator {

    private String sql;
    private String busiCode;
    private Long currentTime;
    private Jedis resource;

    public InterfaceSqlThread(String sql, String busiCode, Long currentTime, Jedis resource) {
        this.sql = sql;
        this.busiCode = busiCode;
        this.currentTime = currentTime;
        this.resource = resource;
    }

    @Override
    public void run() {

        try {
            if (denialOfService()) {
                insertRedis(sql, busiCode, currentTime);
            }
        } finally {
            resource.close();
        }
    }

    /**
     * 插入redis
     * @param sql
     */
    private void insertRedis(String sql, String busiCode, Long currentTime) {
        try {
            Map<String, String> cacheMap = Config.getConfig().getsysConfig();
            String key = cacheMap.get("redis.SQLCollectionQueue");
            String source = cacheMap.get("source");
            //resource.rpop(key);
            resource.lpush(key, source + "||" + busiCode + "||" + currentTime + "||" + sql);
        } catch (Exception e) {
            System.out.println("插入Redis出错" + e.getMessage());
        }
    }

    /**
     * 是否拒绝服务
     * @return
     */
    private boolean denialOfService(){
        try {
            Map<String, String> cacheMap = Config.getConfig().getsysConfig();
            String collectionSwitchKey = cacheMap.get("redis.SQLCollectionSwitch");
            // 如果redis中开关为关闭状态则不进行录制
            String redisSwitch = resource.get(collectionSwitchKey);
            if (redisSwitch.equals("0")) {
                return false;
            }
            Integer collectionCycle = Integer.valueOf(cacheMap.get("redis.SQLCollectionCycle"));
            Integer collectionCount = Integer.valueOf(cacheMap.get("redis.SQLCollectionCount"));
            String collectionKey = cacheMap.get("redis.SQLCollectionKey");
            Long incr = resource.incr(collectionKey);
            if (incr <=1) {
                resource.expire(collectionKey, collectionCycle);
            }
            if(incr <= collectionCount){
                return true;
            }
        } catch (Exception e) {

        }
        return false;
    }
}
